var express = require('express');
var router = express.Router();
const shsDB = require("../db/index.js");


/**
 * 接收信息 存储信息 发布信息 v1
 */
router.post('/message', jwtVerify, (req, res) => {
	// activeItem: {
	// 	fromId: 0, //发送方id
	// 	fromName: "", //发送方名称
	// 	fromUrl: "", //发送方头像
	// 	oldIndex: 0,//上一个
	// 	activeId: 0, //激活id / 接收方id
	// 	isGroup: 1, //是否是群组
	// 	otherName: "社会数官方社会数官方社会数官方社会数官方", //接收方名称
	// 	message: ""
	//	isneed :0 //是否是必须进的群 1是 0||undefined不是
	// }
	const activeItem = Object.assign({}, req.body);
	activeItem.createTime = getdate();
	let obj = {
		code: 200,
		message: "charMsg",
		type: 1, //1：message:2：relationship,3：online
		data: {
			message: "", //业务消息
		}
	}
	if (!activeItem.fromId || !activeItem.fromName || !activeItem.fromUrl || !activeItem.activeId || !activeItem
		.message || activeItem.isGroup === undefined) {
		obj.message = "未按要求传参";
		obj.code = 201;
		res.end(JSON.stringify(obj));
		return;
	}
	let send = Object.assign(obj, {
		data: activeItem
	});
	//添加消息
	let sql =
		`INSERT INTO message(\`Id\`, \`msg\`, \`userId\`, \`otherId\`, \`isGroup\`, \`status\`, \`createTime\`, \`updateTime\`) 
		VALUES (null, ?, ${activeItem.fromId},${activeItem.activeId},${activeItem.isGroup}, 1, '${activeItem.createTime}', '${activeItem.createTime}')`;
	let paramsList = [activeItem.message];
	let lastMsg = activeItem.message.substring(0, 13);
	lastMsg = activeItem.message.length > 14 ? lastMsg + '...' : lastMsg;
	//修改联系人最后一条信息的时间和信息
	let updateSQL = "";
	let updateSQLParams = [lastMsg];
	try {
		if (activeItem.isGroup === 1) {
			//群组 群发
			updateSQL =
				`update grouplastmsg set lastMessage=?,updateTime='${activeItem.createTime}' where groupId=${activeItem.activeId} and status=1`
			if (activeItem.activeId === 1 || activeItem.isneed === 1) {
				//id 1 为所有人必进的群 all推送
				for (client in wsClients) {
					wsClients[client].forEach((client) => {
						client.send(JSON.stringify(send));
					});
				}
				shsDB(sql, paramsList).then(data => {
					try {
						upIntegral(activeItem.fromId, 1)
					} catch (e) {
						//TODO handle the exception
					}
					return shsDB(updateSQL, updateSQLParams)
				}).then(data => {
					res.json(obj);
				}).catch(err => {
					console.log("err 信息添加", err);
					res.json(obj);
				})
			} else {
				//法二：获取群人数再与online比较  
				// 看群人数大还是online人数大
				// online userCount大 按数据库循环online 反之则反
				let selectSql = `select userlist from  shsgroup where Id= ${activeItem.activeId} and status=1;`;
				shsDB(selectSql).then(data => {
					if (data.length === 0) {
						throw new Erroe("data.length===0");
					}
					if (data[0].userlist === undefined || data[0].userlist === null) {
						throw new Erroe("userlist is null");
					}
					let userlist = data[0].userlist.split(',');
					if (userlist.length - 1 < userCount) {
						for (let i = 0; i < userlist.length - 1; i++) {
							let userId = userlist[i];
							if (userId in wsClients) {
								wsClients[userId].forEach((client) => {
									client.send(JSON.stringify(send));
								});
							}
						}
					} else {
						for (client in wsClients) {
							if (userlist.includes(client.toString())) {
								wsClients[client].forEach((client) => {
									client.send(JSON.stringify(send));
								});
							}
						}
					}
					shsDB(sql, paramsList).then(data => {
						try {
							upIntegral(activeItem.fromId, 1)
						} catch (e) {
							//TODO handle the exception
						}
						return shsDB(updateSQL, updateSQLParams)
					}).then(data => {
						res.json(obj);
					}).catch(err => {
						console.log("err 信息添加", err);
						res.json(obj);
					})
				}).catch(err => {
					obj.code = 201;
					if (err === "userlist is null" || err === "data.length===0") {
						obj.message = "无法在封禁的群里发信息"
					} else {
						obj.message = err
						console.log("err 群消息推送", err)
					}
					res.json(obj);
				})
			}
		} else {
			// 单发
			//发送者
			updateSQL =
				`update relationshipuser set lastMessage=?,updateTime='${activeItem.createTime}' where (userId=${activeItem.fromId} and otherId=${activeItem.activeId}) or (userId=${activeItem.activeId} and otherId=${activeItem.fromId}) and status=1`
			wsClients[activeItem.fromId].forEach((client) => {
				client.send(JSON.stringify(send));
			});
			//接收者
			if (wsClients[activeItem.activeId] !== undefined) {
				wsClients[activeItem.activeId].forEach((client) => {
					client.send(JSON.stringify(send));
				});
			}
			shsDB(sql, paramsList).then(data => {
				try {
					upIntegral(activeItem.fromId, 1)
				} catch (e) {
					//TODO handle the exception
				}
				return shsDB(updateSQL, updateSQLParams)
			}).then(data => {
				res.json(obj);
			}).catch(err => {
				console.log("err 信息添加", err);
				res.json(obj);
			})
		}

	} catch (e) {
		//TODO handle the exception
		console.log('判断群聊信息err', e);
	}


});


/**
 * @param {Object} 获取信息
 * @param {Object} res
 * @param {Object} req.param.fromId 用户id  接收人id 页码 数量
 */
router.get('/messageList', jwtVerify, function(req, res, next) {
	let Item = req.query;
	let obj = {
		code: 200,
		message: "",
		type: 1, //1：message:2：relationship,3：online
		data: {
			message: "", //业务消息
		}
	}
	// Item.fromId = req.shsImUserInfo.fromId ? req.shsImUserInfo.fromId : Item.fromId
	Item.fromId = req.shsImUserInfo.fromId //安全性
	if (!Item.fromId || !Item.otherId || Item.isGroup === undefined) {
		obj.message = "未按要求传参";
		obj.code = 201;
		res.end(JSON.stringify(obj));
		return;
	}
	let pageSizes = Item.pageSizes || 50; //条数
	let pageNum = Item.pageNum || 1; //第几页

	let countSql =
		`select count(*) as count from message as msg left join users on users.Id=msg.userId
	where ((msg.userId='${Item.fromId}' and msg.otherId='${Item.otherId}') or (msg.userId='${Item.otherId}' and msg.otherId='${Item.fromId}') ) and msg.status=1 and msg.isGroup='${Item.isGroup}'`
	if (Item.isGroup == 1) {
		countSql = `select count(*) as count
		from message as msg
		left join users on users.Id=msg.userId
		where msg.otherId='${Item.otherId}' and msg.status=1  and msg.isGroup='${Item.isGroup}'`
	}
	shsDB(countSql).then(data => {
		obj.count = data[0].count;
		obj.pageSizes = pageSizes;
		obj.pageNum = pageNum;
		let n = obj.count - pageSizes * pageNum; //pageSizes*(pageNum-1)
		// let pageStart = n > 0 ? n : 0;
		let pageStart = n
		if (n < 0) {
			pageStart = 0
			pageSizes = parseInt(pageSizes) + parseInt(n)
			if (pageSizes < 0) {
				obj.data = [];
				throw new Error("pagesize");
				return
			}
		}
		let select =
			`select msg.Id as messageId,msg.userId as fromId,msg.otherId,msg.isGroup,
		msg.msg as message,msg.status,users.url as fromUrl,users.username as userName,users.gender,msg.type,msg.imagesUrl,msg.createTime,msg.updateTime,msg.dirimagesUrl,msg.msglength
		from message as msg
		left join users on users.Id=msg.userId
		where ((msg.userId='${Item.fromId}' and msg.otherId='${Item.otherId}') or (msg.userId='${Item.otherId}' and msg.otherId='${Item.fromId}')) and msg.status=1  and msg.isGroup='${Item.isGroup}' ORDER BY createTime asc limit ${pageStart},${pageSizes}`;
		if (Item.isGroup == 1) {
			select =
				`select msg.Id as messageId,msg.userId as fromId,msg.otherId,msg.isGroup,
			msg.msg as message,msg.status,users.url as fromUrl,users.username as userName,users.gender,msg.type,msg.imagesUrl,msg.createTime,msg.updateTime,msg.dirimagesUrl,msg.msglength
			from message as msg
			left join users on users.Id=msg.userId
			where  msg.otherId='${Item.otherId}' and msg.isGroup=1 and msg.status=1 ORDER BY createTime asc limit ${pageStart},${pageSizes}`;

		}
		return shsDB(select);
	}).then(data => {
		obj.data = data;
		res.end(JSON.stringify(obj));
	}).catch(err => {
		if (err.message == "pagesize") {
			res.end(JSON.stringify(obj));
		} else {
			obj.code = 201;
			res.end(JSON.stringify(obj));
			console.log('err错误', obj, err.message)
		}
	})
});


module.exports = router;